package github.sf.fw.config;

import com.baomidou.mybatisplus.extension.plugins.inner.InnerInterceptor;
import org.apache.ibatis.executor.Executor;
import org.apache.ibatis.mapping.BoundSql;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.reflection.MetaObject;
import org.apache.ibatis.reflection.SystemMetaObject;
import org.apache.ibatis.session.ResultHandler;
import org.apache.ibatis.session.RowBounds;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.SQLException;
import java.util.Map;

public class ModifyParameterInterceptor implements InnerInterceptor {

    public final static String MYBATIS_PARAM = "param1";
    private final static InsertOrUpdateMetaObjectHandler metaObjectHandler = new InsertOrUpdateMetaObjectHandler();
    private final static Logger logger = LoggerFactory.getLogger(ModifyParameterInterceptor.class);

    @Override
    public void beforeQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
    }

    @Override
    public void beforeUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
    }

    @Override
    public boolean willDoUpdate(Executor executor, MappedStatement ms, Object parameter) throws SQLException {
        SqlCommandType sqlCommandType = ms.getSqlCommandType();
        if (parameter instanceof Map) {
            Object obj = ((Map<?, ?>) parameter).get("param1");
            MetaObject metaObject = SystemMetaObject.forObject(obj);
            switch (sqlCommandType) {
                case INSERT:
                    logger.debug("修改前的参数为{}", parameter);
                    metaObjectHandler.insertFill(metaObject);
                    logger.debug("修改后的参数为{}", parameter);
                case UPDATE:
                    logger.debug("修改前的参数为{}", parameter);
                    metaObjectHandler.updateFill(metaObject);
                    logger.debug("修改后的参数为{}", parameter);
                default:
                    break;
            }

        }
        return true;
    }

    @Override
    public boolean willDoQuery(Executor executor, MappedStatement ms, Object parameter, RowBounds rowBounds, ResultHandler resultHandler, BoundSql boundSql) throws SQLException {
        return true;
    }
}
